#!/bin/bash

work_dir=ssl_certs

root_key=$work_dir/root.key
root_key_pass=111111
root_cert=$work_dir/root.crt
root_dname="/C=CN/ST=GD/L=SZ/O=foo/OU=dev/CN=foo.com/emailAddress=yy@foo.com"

server_key=$work_dir/server.key
server_key_pass=111111
server_csr=$work_dir/server.csr
server_cert=$work_dir/server.crt
server_dname="/C=CN/ST=GD/L=SZ/O=foo/OU=dev/CN=s.foo.com/emailAddress=s@foo.com"

client_key=$work_dir/client.key
client_key_pass=111111
client_csr=$work_dir/client.csr
client_cert=$work_dir/client.crt
client_dname="/C=CN/ST=GD/L=SZ/O=foo/OU=dev/CN=c.foo.com/emailAddress=c@foo.com"

if [ ! -d $work_dir ]; then
    echo "create dir $work_dir"
	mkdir -p $work_dir
else
    echo "clear dir $work_dir"
    rm -r $work_dir/*
fi

echo "generate root key:$root_key"
openssl genrsa -aes256 -passout pass:$root_key_pass -out $root_key 2048

echo "generate root self-auth cert:$root_cert"
openssl req -new -key $root_key -passin pass:$root_key_pass -x509 -days 365 -out $root_cert -subj $root_dname

## generate server cert using ca

echo "generate server key:$server_key"
openssl genrsa -aes256 -passout pass:$server_key_pass -out $server_key 2048

echo "generate server csr:server_csr"
openssl req -new -key $server_key -passin pass:$server_key_pass -out $server_csr -subj $server_dname

echo "generate server cert:$server_cert by csr and root ca"
openssl x509 -req -days 3650 -in $server_csr -CA $root_cert -CAkey $root_key -passin pass:$root_key_pass -CAcreateserial -out $server_cert

# generate client cert using ca

echo "generate client key:$client_key"
openssl genrsa -aes256 -passout pass:$client_key_pass -out $client_key 2048

echo "generate client csr:client_csr"
openssl req -new -key $client_key -passin pass:$client_key_pass -out $client_csr -subj $client_dname

echo "generate client cert:$client_cert by csr and root ca"
openssl x509 -req -days 3650 -in $client_csr -CA $root_cert -CAkey $root_key -passin pass:$root_key_pass -CAcreateserial -out $client_cert

